import axios from 'axios'

const api = axios.create({
  baseURL: '/api'
})

export const createArticle = async (data) => {
  const response = await api.post('/articles', data)
  return response.data
}

export const updateArticle = async (id, data) => {
  const response = await api.put(`/articles/${id}`, data)
  return response.data
}

export const deleteArticle = async (id) => {
  const response = await api.delete(`/articles/${id}`)
  return response.data
}

export const fetchArticle = async (id) => {
  const response = await api.get(`/articles/${id}`)
  return response.data
}

export const fetchArticles = async (params = {}) => {
  try {
    const { page = 1, limit = 10, search = '' } = params
    
    const queryParams = new URLSearchParams()
    queryParams.append('page', page)
    queryParams.append('limit', limit)
    
    if (search) {
      queryParams.append('search', search)
    }
    
    console.log('发送请求到:', `/api/articles?${queryParams.toString()}`)
    
    const response = await fetch(`/api/articles?${queryParams.toString()}`, {
      method: 'GET',
      headers: {
        'Accept': 'application/json',
        'Content-Type': 'application/json'
      }
    })
    
    // 如果是 500 错误，尝试获取更详细的错误信息
    if (response.status === 500) {
      try {
        const errorData = await response.json()
        console.error('服务器错误详情:', errorData)
        // 返回一个空的结果，而不是抛出异常
        return {
          items: [],
          total: 0,
          page: parseInt(page),
          limit: parseInt(limit)
        }
      } catch (parseError) {
        console.error('无法解析错误响应:', parseError)
        // 返回一个空的结果，而不是抛出异常
        return {
          items: [],
          total: 0,
          page: parseInt(page),
          limit: parseInt(limit)
        }
      }
    }
    
    if (!response.ok) {
      console.error('HTTP 错误:', response.status, response.statusText)
      // 返回一个空的结果，而不是抛出异常
      return {
        items: [],
        total: 0,
        page: parseInt(page),
        limit: parseInt(limit)
      }
    }
    
    const data = await response.json()
    console.log('原始响应:', data)
    
    if (!data) {
      console.error('API 返回了空数据')
      // 返回一个空的结果，而不是抛出异常
      return {
        items: [],
        total: 0,
        page: parseInt(page),
        limit: parseInt(limit)
      }
    }
    
    return data
  } catch (error) {
    console.error('API 请求失败:', error)
    // 返回一个空的结果，而不是抛出异常
    return {
      items: [],
      total: 0,
      page: params.page || 1,
      limit: params.limit || 10
    }
  }
}

export const generateArticle = async (modelId, params) => {
  const response = await api.post(`/articles/generate`, {
    model_id: modelId,
    ...params
  })
  return response.data
}

export const saveArticle = async (data) => {
  // 确保使用正确的字段名
  const saveData = {
    ...data,
    // 如果后端 API 仍然期望 topic 字段，可以添加这个转换
    // topic: data.title,
    // 或者如果前端代码仍然使用 topic，可以添加这个转换
    // title: data.topic,
  }
  
  if (data.id) {
    // 更新现有文章
    const response = await api.put(`/articles/${data.id}`, saveData)
    return response.data
  } else {
    // 创建新文章
    const response = await api.post('/articles', saveData)
    return response.data
  }
}

export const publishArticle = async (id) => {
  const response = await api.put(`/articles/${id}/publish`)
  return response.data
}

export const generateArticleContent = async (data) => {
  const response = await api.post('/articles/generate-content', data)
  return response.data
}

export const generateArticleContentStream = async (data, onChunk, onComplete, onError) => {
  try {
    const response = await fetch('/api/articles/generate-content-stream', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify(data)
    })
    
    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`)
    }
    
    const reader = response.body.getReader()
    const decoder = new TextDecoder()
    
    let buffer = ''
    
    while (true) {
      const { value, done } = await reader.read()
      
      if (done) {
        break
      }
      
      buffer += decoder.decode(value, { stream: true })
      
      // 处理 SSE 格式的数据
      const lines = buffer.split('\n\n')
      buffer = lines.pop() || ''
      
      for (const line of lines) {
        if (line.startsWith('data: ')) {
          const data = line.slice(6)
          
          if (data === '[DONE]') {
            onComplete && onComplete()
          } else {
            onChunk && onChunk(data)
          }
        }
      }
    }
  } catch (error) {
    console.error('Stream error:', error)
    onError && onError(error)
  }
}

export const fetchReferenceContent = async (url) => {
  const response = await api.post('/articles/fetch-reference', { url })
  return response.data
}

export const deleteArticleById = async (id) => {
  const response = await api.delete(`/articles/${id}`)
  return response.data
} 